import React from "react";
import { List, Page, Icon, useNavigate, Select } from "zmp-ui";
import { useRecoilValue } from "recoil";
import { userState, authTokenState } from "../state";
import { useI18n } from "../i18n";
import { getLocation } from "zmp-sdk";
import { useUserCenter } from "../hooks/useUserCenter";

import UserCard from "../components/user-card";
import Map from "../components/map";
import Sidebar from "../components/sidebar";

// 导入图标
import iconMenu from "../assets/img/home/icon_menu.png";
import iconList from "../assets/img/home/icon_list.png";
import iconLocation from "../assets/img/home/icon_main_location.png";
import iconScan from "../assets/img/home/icon_main_scan.png";

const HomePage: React.FunctionComponent = () => {
  const user = useRecoilValue(userState);
  const authToken = useRecoilValue(authTokenState);
  const { userCenterData, loading: userCenterLoading, error: userCenterError, refreshUserCenterData } = useUserCenter();
  const { t, locale, setLocale } = useI18n();
  const navigate = useNavigate();
  
  // 侧边栏状态
  const [sidebarOpen, setSidebarOpen] = React.useState(false);
  
  // 地图相关状态
  const [currentLocation, setCurrentLocation] = React.useState<{ lat: number; lng: number } | null>(null);
  const [isLocating, setIsLocating] = React.useState(false);
  const [locationFailed, setLocationFailed] = React.useState(false);
  const [locationInitialized, setLocationInitialized] = React.useState(false);
  
  // 默认位置（胡志明市）
  const defaultLocation = { lat: 10.8231, lng: 106.6297 };
  
  // 页面加载时刷新用户中心数据
  React.useEffect(() => {
    let isMounted = true;
    
    if (authToken && !userCenterData) {
      refreshUserCenterData().catch((error) => {
        if (isMounted) {
          console.error('获取用户中心数据失败:', error);
        }
      });
    }
    
    return () => {
      isMounted = false;
    };
  }, [authToken, userCenterData, refreshUserCenterData]);
  
  // 扫码功能
  const handleScan = () => {
    navigate('/scan');
  };
  
  // 检查权限状态
  const checkPermissionStatus = () => {
    if ('permissions' in navigator) {
      navigator.permissions.query({ name: 'geolocation' }).then((result) => {
        console.log('位置权限状态:', {
          state: result.state,
          granted: result.state === 'granted',
          denied: result.state === 'denied',
          prompt: result.state === 'prompt'
        });
      }).catch((err) => {
        console.log('无法查询权限状态:', err);
      });
    } else {
      console.log('浏览器不支持权限查询API');
    }
  };

  // 静默定位函数 - 使用Zalo SDK
  const silentLocation = () => {
    console.log('开始Zalo SDK静默定位...');
    console.log('Zalo SDK版本信息:', (window as any).ZaloSDK || '未找到ZaloSDK');
    setIsLocating(true);
    
    getLocation({
      success: (data) => {
        console.log('Zalo SDK getLocation成功，完整数据:', data);
        console.log('数据类型:', typeof data);
        console.log('数据字段:', Object.keys(data));
        console.log('数据值:', JSON.stringify(data, null, 2));
        
        // 检查是否有经纬度信息
        if (data.latitude && data.longitude) {
          console.log('找到经纬度信息:', { lat: data.latitude, lng: data.longitude });
          setCurrentLocation({ 
            lat: Number(data.latitude), 
            lng: Number(data.longitude) 
          });
          setIsLocating(false);
          setLocationFailed(false);
          setLocationInitialized(true);
        } else {
          console.log('getLocation返回数据中没有经纬度信息，使用默认位置');
          console.log('可能的原因: 1.权限未授予 2.API配置问题 3.设备不支持');
          setCurrentLocation(defaultLocation);
          setIsLocating(false);
          setLocationFailed(true);
          setLocationInitialized(true);
        }
      },
      fail: (error) => {
        console.log('Zalo SDK getLocation失败，使用默认位置');
        console.log('Zalo SDK错误详情:', {
          errorCode: error.errorCode,
          errorMessage: error.errorMessage,
          errorDetail: error.errorDetail,
          fullError: error
        });
        
        setCurrentLocation(defaultLocation);
        setIsLocating(false);
        setLocationFailed(true);
        setLocationInitialized(true);
      }
    });
  };
  
  // 组件加载时自动定位
  React.useEffect(() => {
    if (!locationInitialized) {
      silentLocation();
    }
  }, [locationInitialized]);
  
  // 重新定位到当前位置 - 使用Zalo SDK
  const handleLocation = () => {
    console.log('用户手动触发Zalo SDK定位...');
    setIsLocating(true);
    
    getLocation({
      success: (data) => {
        console.log('手动Zalo SDK定位成功，完整数据:', data);
        console.log('手动定位数据字段:', Object.keys(data));
        
        // 检查是否有经纬度信息
        if (data.latitude && data.longitude) {
          setCurrentLocation({ 
            lat: Number(data.latitude), 
            lng: Number(data.longitude) 
          });
          setIsLocating(false);
          setLocationFailed(false);
          setLocationInitialized(true);
        } else {
          console.log('手动定位返回数据中没有经纬度信息，使用默认位置');
          setCurrentLocation(defaultLocation);
          setIsLocating(false);
          setLocationFailed(true);
          setLocationInitialized(true);
        }
      },
      fail: (error) => {
        console.log('手动Zalo SDK定位失败，使用默认位置');
        console.log('手动定位错误详情:', {
          errorCode: error.errorCode,
          errorMessage: error.errorMessage,
          errorDetail: error.errorDetail
        });
        
        setCurrentLocation(defaultLocation);
        setIsLocating(false);
        setLocationFailed(true);
        setLocationInitialized(true);
      }
    });
  };

  return (
    <Page className="page" style={{ padding: 0, background: '#f5f5dc' }}>
      <style>
        {`
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        `}
      </style>
      <div style={{
        width: '100%',
        height: '100vh',
        position: 'relative',
        overflow: 'hidden'
      }}>
        {/* 地图区域 */}
        <Map 
          style={{ height: '100%' }} 
          center={currentLocation || defaultLocation}
          onMerchantClick={(merchant) => {
            // 点击商家标记时跳转到商家详情页面
            navigate(`/merchant-detail?siteId=${merchant.id}&distance=${merchant.distance}`);
          }}
        />
        
        {/* 左上角菜单按钮 */}
        <div
          onClick={() => setSidebarOpen(!sidebarOpen)}
          title={t('home.menu')}
          style={{
            position: 'absolute',
            top: 20,
            left: 20,
            width: 44,
            height: 44,
            borderRadius: '50%',
            background: 'rgba(255, 255, 255, 0.9)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
            zIndex: 1000
          }}
        >
          <img 
            src={iconMenu} 
            alt="Menu" 
            style={{ 
              width: 44, 
              height: 44,
              // filter: 'brightness(0) saturate(100%)'
            }} 
          />
        </div>
        
        {/* 右下角功能按钮 */}
        <div style={{
          position: 'absolute',
          bottom: 120,
          right: 20,
          display: 'flex',
          flexDirection: 'column',
          gap: 12,
          zIndex: 1000
        }}>
          {/* 列表按钮 */}
          <div
            onClick={() => navigate("/merchants")}
            title={t('home.orders')}
            style={{
              width: 44,
              height: 44,
              borderRadius: '50%',
              background: 'rgba(255, 255, 255, 0.9)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
            }}
          >
            <img 
              src={iconList} 
              alt="Merchants" 
              style={{ 
                width: 44, 
                height: 44,
                // filter: 'brightness(0) saturate(100%)'
              }} 
            />
          </div>
          
          {/* 定位按钮 */}
          <div
            onClick={handleLocation}
            title={isLocating ? '定位中...' : t('home.location')}
            style={{
              width: 44,
              height: 44,
              borderRadius: '50%',
              background: isLocating ? 'rgba(255, 193, 7, 0.9)' : 'rgba(255, 255, 255, 0.9)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: isLocating ? 'not-allowed' : 'pointer',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              transition: 'all 0.3s ease'
            }}
          >
            {isLocating ? (
              <div style={{
                width: 20,
                height: 20,
                border: '2px solid #fff',
                borderTop: '2px solid transparent',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite'
              }} />
            ) : (
              <img 
                src={iconLocation} 
                alt="Location" 
                style={{ 
                  width: 44, 
                  height: 44,
                  // filter: 'brightness(0) saturate(100%)'
                }} 
              />
            )}
          </div>
        </div>
        
        {/* 底部扫码按钮 */}
        <div
          onClick={handleScan}
          title={t('home.scanButton')}
          style={{
            position: 'absolute',
            bottom: 20,
            left: 20,
            right: 20,
            height: 56,
            background: '#000',
            borderRadius: 28,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
            zIndex: 1000
          }}
        >
          <img 
            src={iconScan} 
            alt="Scan" 
            style={{ 
              width: 24, 
              height: 24,
              marginRight: 12,
              filter: 'brightness(0) invert(1)'
            }} 
          />
          <span style={{
            color: '#fff',
            fontSize: 16,
            fontWeight: 500
          }}>
            {t('home.scanButton')}
          </span>
        </div>
        
        {/* 侧边栏 */}
        <Sidebar 
          isOpen={sidebarOpen} 
          onClose={() => setSidebarOpen(false)} 
        />
      </div>
    </Page>
  );
};

export default HomePage;